﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace Ta_La
{
    public partial class Form1 : Form
    {
        Socket _socketServer, _socketClient;
        List<AClient> _listClient;
        BoBai bobai = new BoBai();
        byte[] _buffer;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            _listClient = new List<AClient>();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Start();
        }
        private List<LaBai> Chia()
        {
            var list = BoBai.Randomize(bobai.list, 9);
            return list;
        }
        private void Start()
        {
            _socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socketServer.Bind(new IPEndPoint(IPAddress.Loopback, 8888));
            _socketServer.Listen(-1);
            try
            {
                _socketServer.BeginAccept(new AsyncCallback(AcceptCallBack), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void AcceptCallBack(IAsyncResult AR)
        {
            try
            {
                _socketClient = _socketServer.EndAccept(AR);
                textBox.AppendText("Có một Client online:  ");
                _socketServer.BeginAccept(new AsyncCallback(AcceptCallBack), null);
                _buffer = new byte[1024];
                _socketClient.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), _socketClient);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void ReceiveCallBack(IAsyncResult AR)
        {
            try
            {
                _socketClient = AR.AsyncState as Socket;
                _socketClient.EndReceive(AR);
                ChatMessage msg = new ChatMessage(_buffer);
                var sendmsg = new ChatMessage(msg.UserName, msg.CmdType, string.Empty);
                byte[] send;

                switch (msg.CmdType)
                {
                    case Command.Login:
                        textBox.AppendText(msg.UserName + "\n");
                        _listClient.Add(new AClient()
                        {
                            Connector = this._socketClient,
                            UserName = msg.UserName
                        });
                        sendmsg.Message = string.Format("<<<{0} da tham gia phong chat>>>", msg.UserName);
                        break;
                    case Command.Logout:
                        break;
                    case Command.List:
                        string listname = null;
                        _listClient.ForEach(p => listname += p.UserName + "*");
                        ChatMessage msglist = new ChatMessage(string.Empty, Command.List, listname);
                        _buffer = msglist.TobyteArray();
                        _socketClient.BeginSend(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
                        break;
                    case Command.Start:
                        string m="";
                        for (int i = 0; i < _listClient.Count; i++)
			            {
                            var list1 = Chia();
                            list1.ForEach(c => m += c.So + " " + c.Ten + "*");
                            msg = new ChatMessage(string.Empty, Command.Start, m);
                            _buffer = msg.TobyteArray();
                            _listClient[i].Connector.BeginSend(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), _listClient[i]);
			            }                              
                        break;
                    case Command.Message:
                        string clientname = msg.UserName;
                        string message = msg.Message;
                        textBox.AppendText(clientname + " says:" + message + "\n");
                        sendmsg.Message = message;
                        break;
                    case Command.Luot:
                        break;
                    case Command.CayRac:
                        break;
                    case Command.Boc:
                        break;
                    case Command.Chot:
                        break;
                    case Command.An:
                        break;
                    case Command.None:
                        break;
                    default:
                        break;
                }
                if (msg.CmdType != Command.List && msg.CmdType != Command.Start)
                {
                    send = sendmsg.TobyteArray();
                    _listClient.ForEach(p =>
                    {
                        if (p.Connector != _socketClient||msg.CmdType!=Command.Login)
                            p.Connector.BeginSend(send, 0, send.Length, SocketFlags.None, new AsyncCallback(SendCallBack), p.Connector);
                    });
                }
                _buffer = new byte[_socketClient.ReceiveBufferSize];
                _socketClient.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), _socketClient);    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void SendCallBack(IAsyncResult AR)
        {
            try
            {
                _socketClient = AR.AsyncState as Socket;
                _socketClient.EndSend(AR);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
